<script setup lang="ts">
import { message } from "ant-design-vue";

interface UserInfo {
  uid?: number;
  nickname?: string;
  phone?: string;
  avatar?: string;
}

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

const user = ref<UserInfo | null>(null);
user.value = useUserInfo().value as UserInfo | null;

const beforeUpload = async (file: File) => {
  const isJpgOrPng =
    file.type === "image/jpeg" ||
    file.type === "image/jpg" ||
    file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("只能上传jpg/png文件!");
    return false; // 阻止上传
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片大小不能超过2M!");
    return false; // 阻止上传
  }
  
  try {
    const formData = new FormData();
    formData.append("avatar", file);
    const { data, error } = await uploadCosFetch({
      method: "POST",
      body: formData,
      key: `uploadCosFetch-${Date.now()}`,
      getCachedData: () => undefined, // 禁用缓存
    });

    if (error.value) {
      console.error("上传头像失败:", error.value);
      if (error.value.statusCode === 401) {
        message.error("请先登录");
        return false;
      }
      message.error("上传失败，请稍后重试");
      return false;
    }

    if (!data.value) {
      message.error("服务器响应异常");
      return false;
    }

    const response = data.value as ApiResponse<{ avatar: string }>;
    if (response.code === 0) {
      if (user.value) {
        user.value.avatar = response.data.avatar;
      }
      const userInfo = useCookie("userInfo", { maxAge: 60 * 60 * 60 * 24 * 7 });
      if (userInfo.value && typeof userInfo.value === 'object') {
        (userInfo.value as UserInfo).avatar = user.value?.avatar;
      }
      message.success("头像上传成功");
      return false; // 阻止默认上传行为，因为我们已经手动上传了
    } else {
      message.error(response.msg || "上传失败");
      return false;
    }
  } catch (err) {
    console.error("上传头像异常:", err);
    message.error("上传过程中发生错误");
    return false;
  }
};

const editUser = async () => {
  if (!user.value) {
    message.error("用户信息不存在");
    return;
  }
  
  try {
    const { data, error } = await editUserFetch({
      method: "PUT", // 修改为 PUT 方法，匹配后端接口
      body: {
        nickname: user.value.nickname || "",
      },
      server: false,
      key: `editUserFetch-${Date.now()}`,
      getCachedData: () => undefined, // 禁用缓存
    });

    if (error.value) {
      console.error("编辑用户失败:", error.value);
      message.error("请求失败，请稍后重试");
      return;
    }

    if (!data.value) {
      message.error("服务器响应异常");
      return;
    }

    const response = data.value as ApiResponse;
    if (response.code === 0) {
      message.success("修改成功");
      const userInfo = useCookie("userInfo", { maxAge: 60 * 60 * 60 * 24 * 7 });
      if (userInfo.value && typeof userInfo.value === 'object' && user.value) {
        (userInfo.value as UserInfo).nickname = user.value.nickname;
      }
    } else {
      message.error(response.msg || "修改失败");
    }
  } catch (err) {
    console.error("编辑用户异常:", err);
    message.error("修改过程中发生错误");
  }
};

useHead({
  title: "个人设置 - 简书",
  meta: [
    {
      name: "description",
      content:
        "简书是一个优质的创作社区，在这里，你可以任性地创作，一篇短文、一张照片、一首诗、一幅画……我们相信，每个人都是生活中的艺术家，有着无穷的创造力。",
    },
    {
      name: "keywords",
      content:
        "简书,简书官网,图文编辑软件,简书下载,图文创作,创作软件,原创社区,小说,散文,写作,阅读",
    },
  ],
});
</script>

<template>
  <Navbar />
  <a-row type="flex" justify="center" class="settings">
    <a-col :span="12">
      <a-row>
        <a-col :span="7" class="aside">
          <div class="user-link-item active">
            <icon-mdi-list-box />
            <span>基础设置</span>
          </div>
          <div class="user-link-item">
            <icon-mdi-account-box />
            <span>个人资料</span>
          </div>
          <div class="user-link-item">
            <icon-mdi-alpha-b-box />
            <span>黑名单</span>
          </div>
        </a-col>
        <a-col :span="17">
          <div class="setting-base">
            <div class="settings-list">
              <div class="item-line">
                <a-avatar :size="85">
                  <template #icon>
                    <img
                      :src="
                        user?.avatar ? user.avatar : '/images/default-avatar.png'
                      "
                      alt="avatar"
                    />
                  </template>
                </a-avatar>
              </div>
              <div>
                <!--                <a-button  shape="round" ghost>更改头像</a-button>-->
                <a-upload
                  name="avatar"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                >
                  <a-button shape="round" ghost>更改头像</a-button>
                </a-upload>
              </div>
            </div>
            <div class="settings-list border-b">
              <div class="item-line">
                <span>昵称</span>
              </div>
              <div class="nickname">
                <a-input
                  :value="user?.nickname || ''"
                  @update:value="(val: string) => { if (user) user.nickname = val; }"
                  style="background-color: #f7f7f7"
                  :bordered="false"
                  placeholder="输入昵称"
                ></a-input>
              </div>
            </div>
            <div class="settings-list border-b">
              <div class="item-line">
                <span>电子邮件</span>
              </div>
              <div>71*****47@qq.com</div>
            </div>
            <div class="settings-list border-b">
              <div class="item-line">
                <span>手机</span>
              </div>
              <div>152****1073</div>
            </div>
            <div class="save-btn">
              <a-button @click="editUser" shape="round" ghost>保存</a-button>
            </div>
          </div>
        </a-col>
      </a-row>
    </a-col>
  </a-row>
</template>

<style lang="scss" scoped>
.settings {
  padding-top: 80px;
  .aside {
    margin-top: 20px;
    .active {
      background-color: #f0f0f0;
      border-radius: 5px;
    }
    .user-link-item {
      padding: 5px 10px;
      display: flex;
      align-items: center;
      &:hover {
        background-color: #f0f0f0;
        border-radius: 5px;
      }
      svg {
        color: #a0a0a0;
        font-size: 32px;
      }
      span {
        font-size: 16px;
        margin-left: 12px;
        color: #333333;
      }
    }
  }
  .setting-base {
    margin-left: 50px;
    .border-b {
      border-bottom: 1px #f0f0f0 solid;
    }
    .settings-list {
      display: flex;
      align-items: center;
      padding: 20px 0;
      .item-line {
        width: 150px;
        span {
          font-size: 15px;
          color: #969696;
        }
      }
      .nickname {
        background-color: #f7f7f7;
        border: 1px solid #c8c8c8;
        border-radius: 6px;
        padding: 2px;
      }
    }
  }
}
</style>
<style>
.settings-list .ant-btn.ant-btn-background-ghost {
  color: #42c02e;
  border-color: #42c02e;
  height: 36px;
}
.save-btn .ant-btn.ant-btn-background-ghost {
  margin-top: 30px;
  color: #ffffff;
  border-color: #42c02e;
  background-color: #00bb29;
  height: 32px;
}
</style>
